var app = angular.module("myapp", ["ngRoute", "ngSanitize", "ui.ace","highcharts-ng",'ui.bootstrap', 'ui.tree']);
//var app = angular.module("myapp", ["ngRoute", "ui.ace"]);

app.controller("ReportListController", function($scope, $http){
    $scope.reportList = [];
    $http.get('/api/reports').success(function(data){
        $scope.reportList = data;
    });
    $scope.reportHtml = "report will be shown here";
    $scope.runReport = function(rptPath){
    //        console.log(rptPath);
            var data = {reportPath: rptPath}
            $http.post('/api/report/html', data)
                .success(function(result){
                    $scope.reportHtml = result.body;
                    console.log($scope.reportHtml);
//                    $location.path("/showReport")
                });
        };
});

app.controller("RunReportController", function($scope, $http, $location){
    $scope.htmlString = '';
    $scope.runReport = function(rptPath){
        $scope.reportPath = rptPath;
//        console.log(rptPath);
        var data = {reportPath: rptPath}
        $http.post('/api/report/html', data)
            .success(function(result){
                $scope.reportHtml = result.body;
                console.log($scope.reportHtml);
                $location.path("/showReport")
            });
    };

});

app.controller("SpecController", function($scope, $http, $modal){
    $scope.reportHtml = "";
    $scope.aceOptions = {
              useWrapMode : true,
              showGutter: true,
              theme:'GitHub',
              mode: 'xml'
        };

    $scope.openModal = function () {
            var modalInstance = $modal.open({
              templateUrl: '/resources/template/cognosReportModalWindow.html',
              controller: CognosReportModalInstanceCtrl,
              windowClass: 'modal-dialog',
              resolve: {
                data: function () {
                  return $scope.data;
                }
              }
            });

            modalInstance.result.then(function (selectedItem) {
              $scope.selected = selectedItem;
            }, function () {
    //          $log.info('Modal dismissed at: ' + new Date());
            });
          };


    $scope.runSpec = function(){
        var data = {spec: $scope.specString} ;
        $http.post('api/spec/html', data)
//        $http.post('api/spec/data', data)
            .success(function(result){
//                console.log(result);
                $scope.reportHtml = result.body;
                //model window
                $scope.data = result.body;
                $scope.openModal();
            }) ;
    };
});

app.controller("EditorController", function($scope, $http, $modal, ModalWindowService){
    $scope.code= '//some code here';
    $scope.aceOptions = {
          useWrapMode : true,
          showGutter: true,
          theme:'GitHub',
          mode: 'groovy'
    };

    $scope.openModal = function () {
                var modalInstance = $modal.open({
                  templateUrl: '/resources/template/cognosReportModalWindow.html',
                  controller: CognosReportModalInstanceCtrl,
                  windowClass: 'modal-dialog',
                  resolve: {
                    data: function () {
                      return $scope.data;
                    }
                  }
                });

                modalInstance.result.then(function (selectedItem) {
                  $scope.selected = selectedItem;
                }, function () {
        //          $log.info('Modal dismissed at: ' + new Date());
                });
     };

    $scope.logCode = function(){
    		console.log($scope.code);
    };
//    $scope.translate = function(){
//          var data={reportPath: $scope.code};
//          $http.post('api/groovySpec/html', data).success(function(result){
//                $scope.reportHtml = result.body;
//                $scope.data = result.body;
////                ModalWindowService.openModal({}, result.body)
//                $scope.openModal();
//          });
//    };
});

app.service("ModalWindowService", function($modal){
    this.openModel = function(options, reportData){
        var defaultOptions = {
          templateUrl: '/resources/template/highchartsModalWindow.html',
          controller: HighChartsModalInstanceCtrl,
          windowClass: 'modal-dialog',
          resolve: {
            data: function () {
              return reportData;
            }
          }
        };

     this.modalInstance = $modal.open(options);
//        modalInstance.result.then(
//            function (selectedItem) {
//                  $scope.selected = selectedItem;
//            },
//            function () {}
//        );
    };

});

app.controller("CustomizationController", function($scope, $http, $modal){
    $scope.code= '//some code here';
//    $scope.chartType = 'line';
    $scope.aceOptions = {
          useWrapMode : true,
          showGutter: true,
          theme:'GitHub',
          mode: 'groovy'
    };
    $scope.openModal = function () {
        var modalInstance = $modal.open({
          templateUrl: '/resources/template/highchartsModalWindow.html',
          controller: HighChartsModalInstanceCtrl,
//          size: size,
          windowClass: 'modal-dialog',
          resolve: {
            data: function () {
              return $scope.data;
            }
          }
        });

        modalInstance.result.then(function (selectedItem) {
          $scope.selected = selectedItem;
        }, function () {
//          $log.info('Modal dismissed at: ' + new Date());
        });
      };

    $scope.getData = function(){
          var data={spec: $scope.code};
          $http.post('api/spec/data', data).success(function(result){
                $scope.data = result;
//                CognosReport.init($scope.data)
//                CognosReport.setType($scope.chartType)
//                $scope.highchartsNG = {
//                    options: CognosReport.options(),
//                    xAxis: CognosReport.xAxis(),
//                    //        yAxis: $scope.yAxis,
//                    series: CognosReport.series(),
//                    title: {
//                        text: CognosReport.corner()
//                    },
//                    loading: false
//                }
                 $scope.openModal();
//                 console.log('opened a modal window')
          });
    };
});

var HighChartsModalInstanceCtrl = function ($scope, $modalInstance, data) {
//  console.log(data)
  $scope.data = data;
  $scope.chartType = 'line';

  $scope.showChart = function(type){
        $scope.chartType = type;
        CognosReport.init($scope.data)
        CognosReport.setType($scope.chartType)
        $scope.highchartsNG = {
            options: CognosReport.options(),
            xAxis: CognosReport.xAxis(),
            //        yAxis: $scope.yAxis,
            series: CognosReport.series(),
            title: {
                text: CognosReport.corner()
            },
            loading: false
        }
  }
  $scope.showChart($scope.chartType)
//  $scope.ok = function () {
//    $modalInstance.close($scope.selected.item);
//  };

  $scope.ok = function () {
    $modalInstance.dismiss('ok');
  };
};

var CognosReportModalInstanceCtrl = function ($scope, $modalInstance, data) {
//  console.log(data)
  $scope.reportHtml = data;
  $scope.ok = function () {
    $modalInstance.dismiss('ok');
  };
};

app.controller("ModelController", function($scope, $http){
    $http.get('/api/models').success(function(data){
//        $scope.model = data.namespaces[0].namespaces;
//        console.log(data)
        $scope.model = data.namespaces;
    });

    $scope.toggle = function(scope) {
      scope.toggle();
    };
});

app.controller("ExcelController", function($scope, $http){
    $scope.isFileUploaded = false
    $scope.isFileTweaked = false;

    $scope.fileChanged = function(element){
        $scope.uploadFile = element.files[0]
        $scope.isFileUploaded = false;
        $scope.isFileTweaked = false;
        $scope.$apply()
    }
    $scope.download = function(){
        $http.get("/file/download").success(function(data){
            console.log("download succeeded")
        })
    }
    $scope.tweak = function(){
        $http.put("/tweakExcel").success(function(data){
            $scope.isFileTweaked = true
            console.log("tweak succeeded")
        })
    }
    $scope.upload=function(){
        var fd = new FormData();
            //Take the first selected file
            fd.append("file", $scope.uploadFile);

            $http.post("/file/upload2", fd, {
                withCredentials: true,
                headers: {'Content-Type': undefined },
                transformRequest: angular.identity
            }).success(function(data, status) {
                console.log("upload succeeded")
                $scope.isFileUploaded = true;
//                def params = {}
//                $http.put("/tweakExcel", params)
//                    .success(function(data, status){
//                        console.log("tweak succeeded")
//                        $http.get("/file/download)
//                    })
            })
            .error(function(data, status) {
                alert("Error ... " + status);
            });
        };
})


app.controller("HeadController", function(){
    //TBD
});

app.config(function ($routeProvider) {
        $routeProvider
            .when('/reports', {templateUrl: '/resources/template/list.html', controller: 'ReportListController'})
            .when('/showReport', {templateUrl: '/resources/template/renderedReport.html', controller: 'RunReportController'})
            .when('/spec', {templateUrl: '/resources/template/spec.html', controller: 'SpecController'})
            .when('/editor', {templateUrl: '/resources/template/editor.html', controller: 'EditorController'})
            .when('/test', {templateUrl: '/resources/template/add.html', controller: 'TestController'})
            .when('/customization', {templateUrl: '/resources/template/customization.html', controller: 'CustomizationController'})
            .when('/models', {templateUrl: '/resources/template/models.html', controller: 'ModelController'})
            .when('/excel', {templateUrl: '/resources/template/excel.html', controller: 'ExcelController'})
            .otherwise({templateUrl: '/resources/template/home.html'});
});


app.controller("TestController", function($scope, $http){
    $scope.a = "";
    $scope.b = "";
    $scope.sum = "";
    $scope.data = '';
    console.log($scope.htmlString);
    $scope.add = function(x, y){
       console.log('a='+$scope.a +", b="+$scope.b)
       $http.post('/api/add', {a:x, b:y}).success(function(result){
            $scope.htmlString = '<h1>hello, world!</h1>';
            $scope.sum = result;
            $http.post('api/spec/data', data).success(function(result){
                            console.log(result);
                            $scope.data = result;
                      });
       } );
    };
});
